from typing import Optional, Dict, Any, List, Awaitable, Callable

from fastapi import APIRouter
from pydantic import BaseModel
from sqlalchemy import select, desc
from sqlalchemy.ext.asyncio import AsyncSession

from common.sqlalchemy_db import SqlalchemyX
from modules.http_resp import PageModel, ResponseFail, ResponseSuccess
from modules.mod import Dialog, Message
from service.DialogService import DialogService
from service.MessageService import MessageService



router = APIRouter()


class MessageReq(BaseModel):
    dialogId: int

@router.get("/history")
async def get_history_messages(dialogId: int, page: int = 1, limit: int = 10):
    async with SqlalchemyX.AsyncSessionLocal() as session:
        dialog_service = DialogService(session)
        dialog = await dialog_service.check_and_get_dialog_mes({"dialog_id":dialogId})
        dialog_target_type = await dialog_service.get_dialog_target_type(dialog)
        history_mes_limit = await dialog_service.get_history_message_by_target_type(
            dialog_target_type,
            dialog,
            {"skip": (page - 1) * limit, "take": limit, "order": {"message_id": "DESC"}  }
        )
        history_mes_all = await dialog_service.get_history_message_by_target_type(dialog_target_type, dialog)
        all_message_count = len(history_mes_all)
        history_messages = await dialog_service.resolve_history_message(history_mes_limit)
        return ResponseSuccess({
                "curPage": page,
                "messageNum": len(history_mes_limit),
                "pageSum": (all_message_count // limit) + (1 if all_message_count % limit > 0 else 0),
                "historyMessages": history_messages
            })



@router.get("/history/guest")
async def get_guest_history_messages(page: int = 1, limit: int = 10):
    async with SqlalchemyX.AsyncSessionLocal() as session:
        message_service = MessageService(session)
        return await message_service.get_default_group_history_messages(page,limit)